<?php

namespace app\admin\controller\user;

use app\admin\model\department\Lists;
use app\admin\model\month\Salary;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员静态资产
 *
 * @icon fa fa-circle-o
 */
class Sign extends Backend
{

    /**
     * Sign模型对象
     * @var \app\admin\model\user\Sign
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Sign;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->param('filter');
            $filter = json_decode($filter, true);
            if (isset($filter['department_name'])) {
                $department_name = $filter['department_name'];
                $ids = Lists::where('name', 'like', '%' . $department_name . '%')->column('id');
                $uids = \app\admin\model\department\User::where('department_id', 'in', $ids)->column('id');
                $map = [
                    'user_id' => ['in', $uids]
                ];
                $list = $this->model
                    ->with(['user'])
                    ->where($map)
                    ->order($sort, $order)
                    ->paginate($limit);
            } else {
                $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }

//            $time = 20 * 60;
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['department_id', 'username', 'nickname']);
                $department_name = Lists::where('id', $row->user->department_id)->value('name');
                $row->department_name = $department_name;

//                $row->is_late = 0;
//                $data = sign_config($row->user_id);
//                unset($data[1], $data[3]);
//                foreach ($data as $val) {
//                    $createtime = strtotime(date('H:i', $row->createtime));
//                    $start = strtotime($val[0]);
//                    $end = strtotime($val[1]);
//                    if ($createtime >= $start && $createtime <= $end) {
//                        if ($createtime >= ($end - $time)) {
//                            $row->is_late = 1;
//                        }
//                    }
//                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $params['createtime'] = strtotime($params['createtime']);

            $result = $this->model->allowField(true)->save($params);

            $userId = $params['user_id'];
            $user = \app\admin\model\department\User::find($userId);
            if ($user->type == 1) {
                $last_mont_first_date = date('Y-m-01', $params['createtime']);
                $last_mont_first_time = strtotime($last_mont_first_date);
                $last_mont_end_date = date("Y-m-d", strtotime("$last_mont_first_date +1 month -1 day"));  //月末
                $last_mont_end_time = strtotime($last_mont_end_date);
                $days = floor(($last_mont_end_time - $last_mont_first_time) / 86400) + 1;

                $signConfig = sign_config($userId);
                $signConfig1 = array_slice($signConfig, 0, 2);
                $signConfig2 = array_slice($signConfig, 2, 2);
                $total_num = 0;
                for ($i = 0; $i < $days; $i++) {
                    $date = date('Y-m-d', $last_mont_first_time + $i * 86400);
                    $num1 = $this->getNum($signConfig1, $userId, $date);
                    $total_num += $num1;

                    $num2 = $this->getNum($signConfig2, $userId, $date);
                    $total_num += $num2;
                }

                $money = round($user->day_salary / 2, 2);
                $salary = $total_num * $money;

                // 员工增加月薪
                $month = strtotime(date('Y-m', $params['createtime']));
                $where = [
                    'user_id' => $userId,
                    'datetime' => $month,
                ];

                $row = Salary::where($where)->find();
                if ($row) {
                    $row->salary = $salary;
                    $row->save();
                } else {
                    $where['salary'] = $salary;
                    $ret = Salary::create($where);
                }

            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 判断是否签到
     * @param $signConfig
     * @param $userId
     * @param $date
     * @return int
     */
    private function getNum($signConfig, $userId, $date)
    {
        $tnum = 0;
        $num1 = 0;
        foreach ($signConfig as $v1) {
            $start1 = strtotime($date . $v1[0]);
            $end1 = strtotime($date . $v1[1]);
            $where = [
                'user_id' => $userId,
                'createtime' => [['>=', $start1], ['<', $end1]]
            ];
            $sign = \app\admin\model\user\Sign::where($where)->find();

            if ($sign) {
                $num1 += 1;
            }

        }

        if ($num1 >= 2) {
            $tnum += 1;
        }

        return $tnum;
    }
}
